<?php
include("include/config.inc.php");
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
	if(isset($_POST['submit']))
	{
	  $partyId   = isset($_REQUEST['partyId']) && $_REQUEST['partyId'] != '' ? $_REQUEST['partyId'] : 0;
	  $orderDate = $_POST['orderDateYear']."-".$_POST['orderDateMonth']."-".$_POST['orderDateDay'];
	  $dueDate   = $_POST['dueDateYear']."-".$_POST['dueDateMonth']."-".$_POST['dueDateDay'];
	  
	  $insertOrder = "INSERT INTO orderItem  (partyId,orderDate,dueDate)
	                                 VALUES (".$partyId.",'".$orderDate."','".$dueDate."')";
	  $insertOrderRes = mysql_query($insertOrder);
	  $lastOrderId = mysql_insert_id();
	  if(!$insertOrderRes)
	  {
	  	echo "Insert Fail";
	  }
	  else
	  {
	  	$loopCount = 0;
      while($loopCount < count($_POST['itemId']))
      {
        $itemId   = isset($_POST['itemId'][$loopCount]) && ($_POST['itemId'][$loopCount] != '') ? $_POST['itemId'][$loopCount] : 0;
        $quantity = isset($_POST['quantity'][$loopCount]) && ($_POST['quantity'][$loopCount] != '') ? $_POST['quantity'][$loopCount] : 0;
         
        if($_POST['itemId'][$loopCount] > 0)
        {
          $detailQuery = "INSERT INTO orderItemDetail (orderId,itemId,quantity)
                                              VALUES (".$lastOrderId.",".$itemId.",".$quantity.")";
          $detailQueryRes = mysql_query($detailQuery);
        }
        $loopCount++;
      }
	     header("Location:order.php");
	  }
	}
	$itemArray = array();
	$i = 0;
	$selectItem = "SELECT itemId,itemName,itemUnit
	                 FROM item
	                ORDER BY itemName";
	$selectItemRes = mysql_query($selectItem);
	while($itemRow = mysql_fetch_array($selectItemRes))
	{
		$itemArray['itemId'][$i]   = $itemRow['itemId'];
		$itemArray['itemName'][$i] = $itemRow['itemName'];
		$i++;
	}
	$partyArray = array();
	$i = 0;
	$selectParty = "SELECT partyId,partyName
	                  FROM party
	                ORDER BY partyName";
	$selectPartyRes = mysql_query($selectParty);
	while($partyRow = mysql_fetch_array($selectPartyRes))
	{
		$partyArray['partyId'][$i]   = $partyRow['partyId'];
		$partyArray['partyName'][$i] = $partyRow['partyName'];
		$i++;
	}
}

include("./bottom.php");
$smarty->assign('itemArray',$itemArray);
$smarty->assign('partyArray',$partyArray);
$smarty->display("order.tpl");
?>